﻿using LitJson;
using System.IO;
using System.Net;
using System.Text;

namespace KzwgRoomTester
{
    public class HttpUtils
    {


        public static string Put(string data, string uri)
        {
            return CommonHttpRequest("PUT", uri, data);
        }

        public static BaseReply<R> Post<R>(string uri, object data)
        {
            var body = JsonMapper.ToJson(data);
            var result = CommonHttpRequest("POST", uri, body);
            return JsonMapper.ToObject<BaseReply<R>>(result);
        }


        public static string Post(string uri, string data)
        {
            return CommonHttpRequest("POST", uri, data);
        }

        public static string CommonHttpRequest(string method, string serviceUrl, string body)
        {
            var myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            var buf = Encoding.GetEncoding("UTF-8").GetBytes(body);

            myRequest.Method = method;
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;

            Stream newStream = myRequest.GetRequestStream();
            newStream.Write(buf, 0, buf.Length);
            newStream.Close();

            var myResponse = (HttpWebResponse)myRequest.GetResponse();
            var reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            var result = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return result;
        }

        public static string Get(string serviceUrl)
        {
            var myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            var myResponse = (HttpWebResponse)myRequest.GetResponse();

            var reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            var result = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return result;
        }
    }
}
